﻿using Aspose.Cells;
using Aspose.Cells.Rendering;
using AWSV2.Models;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.Drawing.Printing;
using System.Windows.Forms;
using System.Linq;
using Newtonsoft.Json;
using System.Data;
using NPOI.SS.Formula.Functions;
using Common.Utility.AJ;
using Common.Utility.AJ.Extension;

namespace AWSV2.Services
{
    public class PrintHelper
    {
        private static Worksheet m_worksheet;
        private static Bitmap printBitmap;

        private static readonly AppSettingsSection _mainSetting = Common.Utility.SettingsHelper.AWSV2Settings;
        private static readonly log4net.ILog log = LogHelper.GetLogger();

        private static readonly Common.Model.AJPrintConfig _aJPrintConfig = AJUtil.TryGetJSONObject<Common.Model.AJPrintConfig>(_mainSetting.Settings[nameof(Common.Model.AJPrintConfig)]?.Value ?? string.Empty) ?? new Common.Model.AJPrintConfig();

        //打印过磅单图片
        public static void PrintImg(WeighingRecordModel record, Worksheet worksheet, string weighingType)
        {

            if (string.IsNullOrWhiteSpace(record?.Bh))
            {
                // 如果编号是空的，就直接不打印了 --阿吉 2023年8月7日09点19分(这里需要增加一个日志)
                log.Debug("磅单异常无法打印");
                return;
            }
            string strPageCount = _mainSetting.Settings["PageCount"]?.Value;
            int iCount = Convert.ToInt32(strPageCount);
            for (int i = 0; i < iCount; i++)
            {
                Print(record, worksheet, weighingType);
            }
        }

        public static void Print(WeighingRecordModel record, Worksheet worksheet, string weighingType)
        {

            string strPageWidth = _mainSetting.Settings["PageSizeWidth"]?.Value;
            string strPageHeight = _mainSetting.Settings["PageSizeHeight"]?.Value;
            int iWidth = Convert.ToInt32(strPageWidth) * 1000 / 254;
            int iHeight = Convert.ToInt32(strPageHeight) * 1000 / 254;

            PrintView(record, worksheet);

            //使用aspose插件将excel转换为图片
            printBitmap = ExcelToBmp(m_worksheet);

            try
            {
                //从数据库中读取配置的自定义纸张大小
                PrintDocument pd = new PrintDocument();
                PaperSize ps = new PaperSize("自定义", iWidth, iHeight);
                //pd.PrinterSettings.Copies = (short)iCount;
                //pd.PrinterSettings.MaximumCopies
                pd.DefaultPageSettings.PaperSize = ps;
                //pd.DefaultPageSettings.Landscape = true;


                pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);

                var printingType = _mainSetting.Settings["PrintingType"]?.Value;

                if ((_mainSetting.Settings["PrintingMode"]?.Value ?? "").Equals("Priview"))
                {
                    if (printingType == "0" &&
                       (weighingType != "FirstWeighing" &&
                       weighingType != "OnceWeighing"))//printingType == "0"是一次过磅打印
                    {
                        //设置为第一次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else if (printingType == "1" &&
                        (weighingType != "SecondWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "1"是二次过磅打印
                    {
                        //设置为第二次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else
                    {

                        PrintPreviewDialog ppd = new PrintPreviewDialog();
                        ppd.WindowState = FormWindowState.Maximized;
                        ppd.Document = pd;
                        ppd.Activate();
                        ppd.ShowDialog();
                        log.Debug($"磅单打印成功：{record}");
                    }
                }
                else
                {

                    string[] pList = (_mainSetting.Settings["Printer"]?.Value ?? "").Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                    if (printingType == "0" &&
                        (weighingType != "FirstWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "0"是一次过磅打印
                    {
                        //设置为第一次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else if (printingType == "1" &&
                        (weighingType != "SecondWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "1"是二次过磅打印
                    {
                        //设置为第二次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else
                    {
                        foreach (var p in pList)
                        {
                            pd.PrinterSettings.PrinterName = p;
                            pd.Print();
                        }
                        log.Debug($"磅单打印成功：{record}");
                    }
                }
            }
            catch (Exception e)
            {
                log.Debug($"磅单打印失败：{e.Message}");
            }
        }

        //打印过磅单图片
        public static void Print1(WeighingRecordModel record, Worksheet worksheet, string weighingType)
        {


            string strPageWidth = _mainSetting.Settings["PageSizeWidth"]?.Value;
            string strPageHeight = _mainSetting.Settings["PageSizeHeight"]?.Value;
            int iWidth = Convert.ToInt32(strPageWidth) * 1000 / 254;
            int iHeight = Convert.ToInt32(strPageHeight) * 1000 / 254;

            Worksheet ws = new Workbook().Worksheets[0];
            ws.Copy(worksheet);
            m_worksheet = ws;

            #region 替换模板中的参数
            //设置替换区域：有内容的区域
            var range = m_worksheet.Cells.MaxDisplayRange;
            string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
            string startCellName = cellRange.Split(':')[0];
            string endCellName = cellRange.Split(':')[1];
            CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
            //替换规则
            FindOptions opts = new FindOptions();
            opts.LookInType = LookInType.Values;
            opts.LookAtType = LookAtType.EntireContent;
            opts.SetRange(area);
            //逐个替换
            Cell cell = null;
            cell = m_worksheet.Cells.Find("_bh", cell, opts);
            cell?.PutValue(record.Bh);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh", cell, opts);
            cell?.PutValue(record.Kh);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh2", cell, opts);
            cell?.PutValue(record.Kh2);

            cell = null;
            cell = m_worksheet.Cells.Find("_kh3", cell, opts);
            cell?.PutValue(record.Kh3);

            cell = null;
            cell = m_worksheet.Cells.Find("_ch", cell, opts);
            cell?.PutValue(record.Ch);

            cell = null;
            cell = m_worksheet.Cells.Find("_wz", cell, opts);
            cell?.PutValue(record.Wz);

            cell = null;
            cell = m_worksheet.Cells.Find("_mz", cell, opts);
            cell?.PutValue(record.Mz);

            cell = null;
            cell = m_worksheet.Cells.Find("_pz", cell, opts);
            cell?.PutValue(record.Pz);

            cell = null;
            cell = m_worksheet.Cells.Find("_jz", cell, opts);
            cell?.PutValue(record.Jz);

            cell = null;
            cell = m_worksheet.Cells.Find("_mzsby", cell, opts);
            cell?.PutValue(record.Mzsby);

            cell = null;
            cell = m_worksheet.Cells.Find("_pzsby", cell, opts);
            cell?.PutValue(record.Pzsby);

            cell = null;
            cell = m_worksheet.Cells.Find("_mzrq", cell, opts);
            DateTime temp = DateTime.Now;
            string Mzrq = record.Mzrq;
            if (!String.IsNullOrWhiteSpace(record.Mzrq) && DateTime.TryParse(record.Mzrq, out temp))
            {
                Mzrq = temp.ToString("HH:mm:ss");
            }
            cell?.PutValue(Mzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_pzrq", cell, opts);
            string Pzrq = record.Pzrq;
            if (!String.IsNullOrWhiteSpace(record.Pzrq) && DateTime.TryParse(record.Pzrq, out temp))
            {
                Pzrq = temp.ToString("HH:mm:ss");
            }
            cell?.PutValue(Pzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_jzrq", cell, opts);
            string Jzrq = record.Jzrq;
            if (!String.IsNullOrWhiteSpace(record.Jzrq) && DateTime.TryParse(record.Jzrq, out temp))
            {
                Jzrq = temp.ToString("HH:mm:ss");
            }
            cell?.PutValue(Jzrq);

            cell = null;
            cell = m_worksheet.Cells.Find("_kz", cell, opts);
            cell?.PutValue(record.Kz);

            cell = null;
            cell = m_worksheet.Cells.Find("_kl", cell, opts);
            cell?.PutValue(record.Kl);

            cell = null;
            cell = m_worksheet.Cells.Find("_sz", cell, opts);
            cell?.PutValue(record.Sz);

            cell = null;
            cell = m_worksheet.Cells.Find("_bz", cell, opts);
            cell?.PutValue(record.Bz);

            cell = null;
            cell = m_worksheet.Cells.Find("_by1", cell, opts);
            cell?.PutValue(record.By1);

            cell = null;
            cell = m_worksheet.Cells.Find("_by2", cell, opts);
            cell?.PutValue(record.By2);

            cell = null;
            cell = m_worksheet.Cells.Find("_by3", cell, opts);
            cell?.PutValue(record.By3);

            cell = null;
            cell = m_worksheet.Cells.Find("_by4", cell, opts);
            cell?.PutValue(record.By4);

            cell = null;
            cell = m_worksheet.Cells.Find("_by5", cell, opts);
            cell?.PutValue(record.By5);

            cell = null;
            cell = m_worksheet.Cells.Find("_by6", cell, opts);
            cell?.PutValue(record.By6);

            cell = null;
            cell = m_worksheet.Cells.Find("_by7", cell, opts);
            cell?.PutValue(record.By7);

            cell = null;
            cell = m_worksheet.Cells.Find("_by8", cell, opts);
            cell?.PutValue(record.By8);

            cell = null;
            cell = m_worksheet.Cells.Find("_by9", cell, opts);
            cell?.PutValue(record.By9);

            cell = null;
            cell = m_worksheet.Cells.Find("_by10", cell, opts);
            cell?.PutValue(record.By10);

            cell = null;
            cell = m_worksheet.Cells.Find("_by11", cell, opts);
            cell?.PutValue(record.By11);

            cell = null;
            cell = m_worksheet.Cells.Find("_by12", cell, opts);
            cell?.PutValue(record.By12);

            cell = null;
            cell = m_worksheet.Cells.Find("_by13", cell, opts);
            cell?.PutValue(record.By13);

            cell = null;
            cell = m_worksheet.Cells.Find("_by14", cell, opts);
            cell?.PutValue(record.By14);

            cell = null;
            cell = m_worksheet.Cells.Find("_by15", cell, opts);
            cell?.PutValue(record.By15);

            cell = null;
            cell = m_worksheet.Cells.Find("_by16", cell, opts);
            cell?.PutValue(record.By16);

            cell = null;
            cell = m_worksheet.Cells.Find("_by17", cell, opts);
            cell?.PutValue(record.By17);

            cell = null;
            cell = m_worksheet.Cells.Find("_by18", cell, opts);
            cell?.PutValue(record.By18);

            cell = null;
            cell = m_worksheet.Cells.Find("_by19", cell, opts);
            cell?.PutValue(record.By19);

            cell = null;
            cell = m_worksheet.Cells.Find("_by20", cell, opts);
            cell?.PutValue(record.By20);

            cell = null;
            cell = m_worksheet.Cells.Find("_weighName", cell, opts);
            cell?.PutValue(record.WeighName);

            cell = null;
            cell = m_worksheet.Cells.Find("_weigh2Name", cell, opts);
            cell?.PutValue(record.Weigh2Name);

            cell = null;
            cell = m_worksheet.Cells.Find("_dyrq", cell, opts);
            cell?.PutValue(record.Dyrq);

            //2022-05-25新增一下内容 By:汪虎
            cell = null;
            cell = m_worksheet.Cells.Find("_gblx", cell, opts);
            cell?.PutValue(record.Gblx);

            cell = null;
            cell = m_worksheet.Cells.Find("_je", cell, opts);
            cell?.PutValue(record.Je);

            cell = null;
            cell = m_worksheet.Cells.Find("_axleNum", cell, opts);
            cell?.PutValue(record.AxleNum);

            cell = null;
            cell = m_worksheet.Cells.Find("_amount", cell, opts);
            cell?.PutValue(record.Amount);

            cell = null;
            cell = m_worksheet.Cells.Find("_credit", cell, opts);
            cell?.PutValue(record.Credit);

            cell = null;
            cell = m_worksheet.Cells.Find("_weigh", cell, opts);
            cell?.PutValue(record.Weigh);

            cell = null;
            cell = m_worksheet.Cells.Find("_isLimit", cell, opts);
            cell?.PutValue(record.IsLimit ? "是" : "否");

            cell = null;
            cell = m_worksheet.Cells.Find("_isCover", cell, opts);
            cell?.PutValue(record.IsCover.GetValueOrDefault() ? "是" : "否");

            cell = null;
            cell = m_worksheet.Cells.Find("_iccard", cell, opts);
            cell?.PutValue(record.ICCard);

            cell = null;
            cell = m_worksheet.Cells.Find("_isPay", cell, opts);
            cell?.PutValue(record.IsPay == 1 ? "电子支付" : record.IsPay == 2 ? "线下支付" : record.IsPay == 3 ? "储值支付" : record.IsPay == 4 ? "免费放行" : "未支付");

            //新增打印此车当日总车次总毛净重
            cell = ws.Cells.Find("{weighcount}", cell, opts);

            if (cell != null)
            {
                string date = System.DateTime.Now.ToString("yyyy-MM-dd");
                var list = SQLDataAccess.LoadWeighingRecordCount(record.Ch, date);
                decimal mzcount = 0;
                decimal jzcount = 0;
                foreach (var item in list)
                {
                    mzcount += Convert.ToDecimal(item.Mz);
                    jzcount += Convert.ToDecimal(item.Jz);
                }
                cell.Value = $"{date}:车号{record.Ch},总车次{list.Count},总毛重{mzcount},总净重{jzcount}"; ;
            }
            #endregion

            //使用aspose插件将excel转换为图片
            printBitmap = ExcelToBmp(m_worksheet);

            try
            {
                //从数据库中读取配置的自定义纸张大小
                PrintDocument pd = new PrintDocument();
                PaperSize ps = new PaperSize("自定义", iWidth, iHeight);
                //pd.PrinterSettings.Copies = (short)iCount;
                //pd.PrinterSettings.MaximumCopies
                pd.DefaultPageSettings.PaperSize = ps;
                //pd.DefaultPageSettings.Landscape = true;


                pd.PrintPage += new PrintPageEventHandler(Pd_PrintPage);

                var printingType = _mainSetting.Settings["PrintingType"]?.Value;

                if ((_mainSetting.Settings["PrintingMode"]?.Value ?? "").Equals("Priview"))
                {
                    if (printingType == "0" &&
                       (weighingType != "FirstWeighing" &&
                       weighingType != "OnceWeighing"))//printingType == "0"是一次过磅打印
                    {
                        //设置为第一次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else if (printingType == "1" &&
                        (weighingType != "SecondWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "1"是二次过磅打印
                    {
                        //设置为第二次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else
                    {

                        PrintPreviewDialog ppd = new PrintPreviewDialog();
                        ppd.WindowState = FormWindowState.Maximized;
                        ppd.Document = pd;
                        ppd.Activate();
                        ppd.ShowDialog();
                    }
                }
                else
                {

                    string[] pList = (_mainSetting.Settings["Printer"]?.Value ?? "").Split(new string[] { ", " }, StringSplitOptions.RemoveEmptyEntries);
                    if (printingType == "0" &&
                        (weighingType != "FirstWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "0"是一次过磅打印
                    {
                        //设置为第一次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else if (printingType == "1" &&
                        (weighingType != "SecondWeighing" &&
                        weighingType != "OnceWeighing"))//printingType == "1"是二次过磅打印
                    {
                        //设置为第二次称重完成,但不是第二次沉重发过来的,那么就阻止打印
                        return;
                    }
                    else
                    {
                        foreach (var p in pList)
                        {
                            pd.PrinterSettings.PrinterName = p;
                            pd.Print();
                        }
                    }
                }
            }
            catch (Exception)
            {

            }
        }

        public static Bitmap PrintView(WeighingRecordModel record, Worksheet worksheet)
        {

            string strPageWidth = _mainSetting.Settings["PageSizeWidth"]?.Value;
            string strPageHeight = _mainSetting.Settings["PageSizeHeight"]?.Value;
            int iWidth = Convert.ToInt32(strPageWidth) * 1000 / 254;
            int iHeight = Convert.ToInt32(strPageHeight) * 1000 / 254;

            Worksheet ws = new Workbook().Worksheets[0];
            ws.Copy(worksheet);
            m_worksheet = ws;

            #region 替换模板中的参数
            //设置替换区域：有内容的区域
            var range = m_worksheet.Cells.MaxDisplayRange;
            string cellRange = range.RefersTo.Split('!')[1].Replace("$", "");
            string startCellName = cellRange.Split(':')[0];
            string endCellName = cellRange.Split(':')[1];
            CellArea area = CellArea.CreateCellArea(startCellName, endCellName);
            //替换规则
            FindOptions opts = new FindOptions();
            opts.LookInType = LookInType.Values;
            opts.LookAtType = LookAtType.EntireContent;
            opts.SetRange(area);

            //逐个替换
            m_worksheet.Replace("_bh", record.Bh);
            m_worksheet.Replace("_kh", record.Kh);
            m_worksheet.Replace("_kh2", record.Kh2);
            m_worksheet.Replace("_kh3", record.Kh3);
            m_worksheet.Replace("_ch", record.Ch);

            m_worksheet.Replace("_mzsby", record.Mzsby);
            m_worksheet.Replace("_pzsby", record.Pzsby);
            m_worksheet.Replace("_goodsSpec", record.GoodsSpec);
            m_worksheet.Replace("_fhdw", record.Fhdw);

            DateTime temp = DateTime.Now;
            string Mzrq = record.Mzrq;
            if (!String.IsNullOrWhiteSpace(record.Mzrq) && DateTime.TryParse(record.Mzrq, out temp))
            {
                //Mzrq = temp.ToString("HH:mm:ss");
                //Mzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
                string formart = _mainSetting.Settings["Mzrqgs"].Value;
                Mzrq = _aJPrintConfig.IsDateUpper ? temp.ToChineseUpper() : temp.ToString(formart);
            }
            m_worksheet.Replace("_mzrq", Mzrq);


            string Pzrq = record.Pzrq;
            if (!String.IsNullOrWhiteSpace(record.Pzrq) && DateTime.TryParse(record.Pzrq, out temp))
            {
                //Pzrq = temp.ToString("HH:mm:ss");
                //Pzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
                string formart = _mainSetting.Settings["Pzrqgs"].Value;
                Pzrq = _aJPrintConfig.IsDateUpper ? temp.ToChineseUpper() : temp.ToString(formart);
            }
            m_worksheet.Replace("_pzrq", Pzrq);


            string Jzrq = record.Jzrq;
            if (!String.IsNullOrWhiteSpace(record.Jzrq) && DateTime.TryParse(record.Jzrq, out temp))
            {
                //Jzrq = temp.ToString("HH:mm:ss");
                //Jzrq = temp.ToString("yyyy年MM月dd日 HH:mm:ss");
                string formart = _mainSetting.Settings["Jzrqgs"].Value;
                Jzrq = _aJPrintConfig.IsDateUpper ? temp.ToChineseUpper() : temp.ToString(formart);
            }
            m_worksheet.Replace("_jzrq", Jzrq);

            string dyrq = record.Dyrq;
            if (!String.IsNullOrWhiteSpace(record.Dyrq) && DateTime.TryParse(record.Dyrq, out temp))
            {
                string formart = _mainSetting.Settings["Dyrqgs"].Value;
                dyrq = _aJPrintConfig.IsDateUpper ? temp.ToChineseUpper() : temp.ToString(formart);
            }
            m_worksheet.Replace("_dyrq", dyrq);
            m_worksheet.Replace("_jz", _aJPrintConfig.IsWeightNumberUpper
                ? DigitToChineseText.Convert(record.Jz.TryGetDecimal().ToString(), false) : record.Jz);
            m_worksheet.Replace("_kz", record.Kz);
            m_worksheet.Replace("_kl", record.Kl);
            m_worksheet.Replace("_sz", record.Sz);
            m_worksheet.Replace("_bz", record.Bz);
            m_worksheet.Replace("_by1", record.By1);
            m_worksheet.Replace("_by2", record.By2);
            m_worksheet.Replace("_by3", record.By3);
            m_worksheet.Replace("_by4", record.By4);
            m_worksheet.Replace("_by5", record.By5);
            m_worksheet.Replace("_by6", record.By6);
            m_worksheet.Replace("_by7", record.By7);
            m_worksheet.Replace("_by8", record.By8);
            m_worksheet.Replace("_by9", record.By9);
            m_worksheet.Replace("_by10", record.By10);
            m_worksheet.Replace("_by11", record.By11);
            m_worksheet.Replace("_by12", record.By12);
            m_worksheet.Replace("_by13", record.By13);
            m_worksheet.Replace("_by14", record.By14);
            m_worksheet.Replace("_by15", record.By15);
            m_worksheet.Replace("_by16", record.By16);
            m_worksheet.Replace("_by17", record.By17);
            m_worksheet.Replace("_by18", record.By18);
            m_worksheet.Replace("_by19", record.By19);
            m_worksheet.Replace("_by20", record.By20);
            m_worksheet.Replace("_weighName", record.WeighName);
            m_worksheet.Replace("_weigh2Name", record.Weigh2Name);

            m_worksheet.Replace("_gblx", record.Gblx);
            m_worksheet.Replace("_je", record.Je);
            m_worksheet.Replace("_dj", record.GoodsPrice.ToString());
            m_worksheet.Replace("_axleNum", record.AxleNum);
            m_worksheet.Replace("_amount", record.Amount + "");
            m_worksheet.Replace("_credit", record.Credit + "");
            m_worksheet.Replace("_weigh", record.Weigh + "");
            m_worksheet.Replace("_weigh", record.Weigh + "");

            m_worksheet.Replace("_wz", record.Wz);
            m_worksheet.Replace("_mz", _aJPrintConfig.IsWeightNumberUpper
                ? DigitToChineseText.Convert(record.Mz.TryGetDecimal().ToString(), false) : record.Mz);
            m_worksheet.Replace("_pz", _aJPrintConfig.IsWeightNumberUpper
                ? DigitToChineseText.Convert(record.Pz.TryGetDecimal().ToString(), false) : record.Pz);

            //2022-11-03新增打印字段
            m_worksheet.Replace("_driver", record.Driver);
            m_worksheet.Replace("_driverPhone", record.DriverPhone);
            m_worksheet.Replace("_entryTime", record.EntryTime.HasValue ? record.EntryTime.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty);
            m_worksheet.Replace("_zflsh", record.Zflsh);
            m_worksheet.Replace("_zfje", record.Zfje.ToString());
            m_worksheet.Replace("_zfsj", record.Zfsj.HasValue ? record.Zfsj.Value.ToString("yyyy-MM-dd HH:mm:ss") : string.Empty);
            m_worksheet.Replace("_limitType", record.LimitType);
            m_worksheet.Replace("_limitedValue", record.LimitedValue);
            m_worksheet.Replace("_serialNumber", record.SerialNumber);

            m_worksheet.Replace("_isLimit", record.IsLimit ? "是" : "否");
            m_worksheet.Replace("_isCover", record.IsCover.GetValueOrDefault() ? "是" : "否");
            m_worksheet.Replace("_iccard", record.ICCard);
            m_worksheet.Replace("_isPay", record.IsPay == 1 ? "电子支付" : record.IsPay == 2 ? "线下支付" : record.IsPay == 3 ? "储值支付" : record.IsPay == 4 ? "免费放行" : "未支付");

            //磅单的二维码图片生成
            Cell qrcodrCell = null;
            qrcodrCell = m_worksheet.Cells.Find("##QRCODE##", qrcodrCell, opts);
            if (qrcodrCell != null)
            {
                //生成磅单二维码的数据集合
                Cells cells = m_worksheet.Cells;
                int maxRow = cells.MaxRow + 1;
                int maxColumn = cells.MaxColumn + 1;
                var tempTable = cells.ExportDataTable(0, 0, maxRow, maxColumn);
                Dictionary<string, string> cellsList = new Dictionary<string, string>();
                var dicts = tempTable.AsEnumerable().Select(p => p.ItemArray.AsEnumerable().Where(f => f != null).ToList()).ToList();

                dicts.ForEach((p) =>
                {
                    p.ForEach((sp =>
                    {
                        var cellName = _mainSetting.Settings[sp.ToString()]?.Value ?? "";
                        if (!string.IsNullOrWhiteSpace(cellName) && !cellsList.ContainsKey(cellName))
                        {
                            cellsList.Add(cellName, sp.ToString());
                        }
                    }));
                });

                //开始生成磅单集合对象的Json格式数据
                string baseStr = JsonConvert.SerializeObject(dicts);
                byte[] b = System.Text.Encoding.Default.GetBytes(baseStr);
                //baseStr= Convert.ToBase64String(b);
                //baseStr = "AAAAAAAABBBBBBBBBBCCCCCCCCCC";
                //根据Json格式数据生成二维码图片流
                var stream = Common.Utility.ImageHelper.CreateCodeStream(baseStr);
                int iIndex = m_worksheet.Pictures.Add(qrcodrCell.Row, qrcodrCell.Column, stream);
                Aspose.Cells.Drawing.Picture pic = m_worksheet.Pictures[iIndex];
                pic.Placement = Aspose.Cells.Drawing.PlacementType.FreeFloating;
                pic.Width = 170;
                pic.Height = 170;
                pic.BorderLineColor = Color.White;
                pic.BorderWeight = 1;
            }

            //新增打印此车当日总车次总毛净重
            Cell cell = null;
            cell = ws.Cells.Find("{weighcount}", cell, opts);
            if (cell != null)
            {
                string date = System.DateTime.Now.ToString("yyyy-MM-dd");
                var list = SQLDataAccess.LoadWeighingRecordCount(record.Ch, date);
                decimal mzcount = 0;
                decimal jzcount = 0;
                foreach (var item in list)
                {
                    mzcount += Convert.ToDecimal(item.Mz);
                    jzcount += Convert.ToDecimal(item.Jz);
                }
                cell.Value = $"{date}:车号{record.Ch},总车次{list.Count},总毛重{mzcount},总净重{jzcount}"; ;
            }
            #endregion

            //使用aspose插件将excel转换为图片
            return ExcelToBmp(m_worksheet);

        }

        //打印eventhandler
        private static void Pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            ev.Graphics.DrawImage(printBitmap, 0, 0);
            ev.HasMorePages = false;
        }

        //使用aspose插件将excel转换为图片
        public static Bitmap ExcelToBmp(Worksheet m_worksheet)
        {
            ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();
            imgOptions.OnePagePerSheet = true;
            SheetRender sr = new SheetRender(m_worksheet, imgOptions);
            Bitmap bitmap = sr.ToImage(0);

            //int actualImgWidth = bitmap.Size.Width - 100;
            //int actualImgHeight = bitmap.Size.Height - 100;
            //Bitmap printBitmap = new Bitmap(actualImgWidth, actualImgHeight);

            //Graphics graphic = Graphics.FromImage(printBitmap);
            //graphic.DrawImage(bitmap, 0, 0, new Rectangle(50, 50, actualImgWidth, actualImgHeight), GraphicsUnit.Pixel);

            //return printBitmap;
            return bitmap;
        }

    }
}
